package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XScrollView;
import com.kpx.app.R;
import com.kpx.app.adapter.PhotoAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.CertificationInfoBean;
import com.kpx.app.bean.GirlItemData;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.Page;
import com.kpx.app.bean.PhotoPicBean;
import com.kpx.app.bean.UploadBean;
import com.kpx.app.cache.FileCache;
import com.kpx.app.configs.BroadcastFilters;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.ImageLoader;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.AutoSizeGridView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.PhotoPreviewActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by congdy on 17/3/7.
 * 我的照片
 */

public class ActivityMyPhotosNew extends ActivityBase {

    @BindView(R.id.type_item_fab)
    ImageView typeItemFab;
    @BindView(R.id.gv_show)
    AutoSizeGridView gvShow;
    @BindView(R.id.out_view)
    XRefreshView outView;
    @BindView(R.id.txt_empty_mention)
    TextView txtEmptyMention;
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.ll_head)
    LinearLayout ll_head;

    protected static final String SUB_TYPE = "subtype";
    @BindView(R.id.gv_show2)
    AutoSizeGridView gvShow2;
    @BindView(R.id.img_hide)
    ImageView imgHide;
    @BindView(R.id.ll_show_mention)
    LinearLayout llShowMention;
    @BindView(R.id.xscl)
    XScrollView xscl;
    private List<GirlItemData> data = new ArrayList<>();
    private List<PhotoInfo> selectedPic = new ArrayList<PhotoInfo>();
    private List<PhotoPicBean> photos = new ArrayList<>();
    private List<PhotoPicBean> photos2 = new ArrayList<>();
    private int pageIndex = 1;
    private int pageSize = 20;
    private Page page;
    private boolean isRefresh = true;
    private PhotoAdapter adapter;
    private boolean isShowEdit;
    private PhotoAdapter adapter2;
    private boolean isLoading = false;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.fragment_type_item_layout_new);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "我的图片");
        UIUtils.initRefreshView(outView);
        outView.setAutoRefresh(false);
        adapter = new PhotoAdapter(ActivityMyPhotosNew.this, photos, R.layout.item_photo_show, 0, isShowEdit);
        setHead();
        setContent();
        setAddPic();
        fetchData();
        imgHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llShowMention.setVisibility(View.GONE);
            }
        });
        titleview.setRight("编辑", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowEdit = !isShowEdit;
                adapter.setIsShowEdit(isShowEdit);
                if (adapter2 != null) {
                    adapter2.setIsShowEdit(isShowEdit);
                }
            }
        }, R.color.white);
    }

    private void setAddPic() {
        typeItemFab.setBackgroundColor(getResources().getColor(R.color.transparent));
        typeItemFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestToCamera(new OnGetCameraPermissionBack() {
                    @Override
                    public void back() {
                        UIUtils.getPhotos(9, selectedPic, new GalleryFinal.OnHanlderResultCallback() {
                            @Override
                            public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                if (resultList != null && resultList.size() > 0) {
                                    ArrayList<UploadBean> ulist = new ArrayList<UploadBean>();
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                                    LoginUser loginUser = UserInfoUtils.getCachedLoginUser();
                                    for (int i = 0; i < resultList.size(); i++) {
                                        UploadBean uploadBean = new UploadBean();
                                        uploadBean.setLocalPath(resultList.get(i).getPhotoPath());
                                        uploadBean.setUploadType(UploadBean.TYPE_PHOTO_IMG);
                                        uploadBean.setImageID(System.currentTimeMillis());
                                        uploadBean.setTitleName("相册图片上传"+(new File(resultList.get(i).getPhotoPath()).length()/1024));
                                        uploadBean.bucketName = UserInfoUtils.getCachedLoginUser().getACCOUNTCONFIG().getBucketone();
                                        uploadBean.createTime = System.currentTimeMillis();
                                        try {
                                            Thread.sleep(2);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        String[] date = df.format(new Date()).split("-");
                                        uploadBean.cloudKey = date[0] + date[1] + "/" + date[2] + "/" + loginUser.getUSER().getDmId() + StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
                                        ulist.add(uploadBean);
                                    }
                                    FileCache.sharedInstance().put(Constants.KEY_UPLOADS_CACHE_LIST, ulist);
                                    sendBroadcast(new Intent(BroadcastFilters.BROADCAST_ACTION_UPLOAD_ADD_PHOTOS));
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("isPhoto", 1);
                                    IntentUtil.gotoActivity(ActivityMyPhotosNew.this, ActivityUploadManager.class, bundle);
                                }
                            }

                            @Override
                            public void onHanlderFailure(int requestCode, String errorMsg) {

                            }
                        });
                    }
                });
            }
        });
    }

    private void setContent() {
        gvShow.setAdapter(adapter);
        gvShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ActivityMyPhotosNew.this, PhotoPreviewActivity.class);
                ArrayList<PhotoInfo> list = new ArrayList<PhotoInfo>();
                PhotoInfo p = new PhotoInfo();
                p.setPhotoPath(photos.get(position).getImgurl());
                Bitmap bitmap = ImageLoader.load(ActivityMyPhotosNew.this, p.getPhotoPath());
                if (bitmap != null) {
                    p.setWidth(bitmap.getWidth());
                    p.setHeight(bitmap.getHeight());
                }
                list.add(p);
                intent.putExtra(PhotoPreviewActivity.PHOTO_LIST, list);
                startActivity(intent);
            }
        });
        outView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                pageIndex = 1;
                fetchData();// 获取数据
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isRefresh = false;
                if (page != null && page.getNextPage() == 0) {
                    ToastUtil.getInstance().showToast(ActivityMyPhotosNew.this, "没有更多了");
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            outView.stopLoadMore();
                        }
                    }, 600);
                    return;
                }
                pageIndex++;
                fetchData();
            }
        });
    }

    private void setHead() {
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    CertificationInfoBean cerb = (CertificationInfoBean) result.getData();
                    if (cerb != null) {
                        if (cerb != null && cerb.getPhotosAuthenStatus() == 1 && cerb.getImsAuthenRecord() != null) {
                            ll_head.setVisibility(View.VISIBLE);
                            addPhotoBean(cerb.getImsAuthenRecord().getSelfieImg());
                            addPhotoBean(cerb.getImsAuthenRecord().getSideImg());
                            addPhotoBean(cerb.getImsAuthenRecord().getFaceImg());
                            addPhotoBean(cerb.getImsAuthenRecord().getEntiretyImg());
                            addPhotoBean(cerb.getImsAuthenRecord().getSideImg());
                            if(cerb.getImsAuthenRecord().getSelfieImg().equals(cerb.getImsAuthenRecord().getSpecifyPhoto())){
                                photos2.get(0).setIsshow(1);
                            }else if(cerb.getImsAuthenRecord().getSideImg().equals(cerb.getImsAuthenRecord().getSpecifyPhoto())){
                                photos2.get(1).setIsshow(1);
                            }else if(cerb.getImsAuthenRecord().getFaceImg().equals(cerb.getImsAuthenRecord().getSpecifyPhoto())){
                                photos2.get(2).setIsshow(1);
                            }else if(cerb.getImsAuthenRecord().getEntiretyImg().equals(cerb.getImsAuthenRecord().getSpecifyPhoto())){
                                photos2.get(3).setIsshow(1);
                            }else if(cerb.getImsAuthenRecord().getSideImg().equals(cerb.getImsAuthenRecord().getSpecifyPhoto())){
                                photos2.get(4).setIsshow(1);
                            }
                            adapter2 = new PhotoAdapter(ActivityMyPhotosNew.this, photos2, R.layout.item_photo_show, 1, isShowEdit);
                            gvShow2.setAdapter(adapter2);
                            gvShow2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Intent intent = new Intent(ActivityMyPhotosNew.this, PhotoPreviewActivity.class);
                                    ArrayList<PhotoInfo> list = new ArrayList<PhotoInfo>();
                                    PhotoInfo p = new PhotoInfo();
                                    p.setPhotoPath(photos2.get(position).getImgurl());
                                    Bitmap bitmap = ImageLoader.load(ActivityMyPhotosNew.this, p.getPhotoPath());
                                    if (bitmap != null) {
                                        p.setWidth(bitmap.getWidth());
                                        p.setHeight(bitmap.getHeight());
                                    }
                                    list.add(p);
                                    intent.putExtra(PhotoPreviewActivity.PHOTO_LIST, list);
                                    startActivity(intent);
                                }
                            });
                            xscl.scrollTo(0, 0);
                        }
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityMyPhotosNew.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityMyPhotosNew.this, error);
            }

        }, CertificationInfoBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_CHECK_CERTIFICATION, true, map);
    }

    private void addPhotoBean(String selfieImg) {
        PhotoPicBean p1 = new PhotoPicBean();
        p1.setImgurl(selfieImg);
        photos2.add(p1);
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        data.clear();
        isRefresh = true;
        pageIndex = 1;
        fetchData();
    }

    protected void fetchData() {
        if(isLoading){
            return;
        }
        isLoading = true;
        showLoadingDialog();//pageIndex, pageSize 分页信息
        MyHashMap map = new MyHashMap();
        map.put("pageIndex", pageIndex + "");
        map.put("pageSize", pageSize + "");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                isLoading = false;
                dissmissLoadingDialog();
                if (isRefresh) {
                    outView.stopRefresh();
                } else {
                    outView.stopLoadMore();
                }
                if (result.getCode() == 0) {
                    page = result.getPage();
                    ArrayList<PhotoPicBean> tem = (ArrayList<PhotoPicBean>) result.getData();
                    if (tem != null && tem.size() > 0) {
                        if (isRefresh) {
                            photos.clear();
                        }
                        photos.addAll(tem);
                        adapter.setData(photos);
                        if (pageIndex==1) {
                            xscl.scrollTo(0, 0);
                        }
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityMyPhotosNew.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                isLoading = false;
                if (isRefresh) {
                    outView.stopRefresh();
                } else {
                    outView.stopLoadMore();
                }
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityMyPhotosNew.this, error);
            }

        }, PhotoPicBean.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_PHOTOS, true, map);
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
